import React, { Component } from 'react'
import { withRouter } from "react-router-dom"
import { Card, Form, Input, Select, Button, message } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import http from "../../../api"
// 富文本器
import E from 'wangeditor'
import Upload from "../../../components/Upload"
import "./index.css"

const { Option } = Select
const { Item } = Form
let editor = null

class AddUpdata extends Component {
  uploadRef = React.createRef()
  state = { name: '', status: true, imgs: [], desc: '', price: 0, detail: '', category: [] }
  // 返回商品管理页
  historyGo = () => {
    this.props.history.go(-1)
  }
  // 提交或修改表单回调
  submitForm = () => {
    if(!this.state.name) return message.error('商品名称必须填写！')
    // 获取图片地址
    const { fileList } = this.uploadRef.current.state
    // 获取富文本的内容
    const detail = editor.txt.html()
    this.setState({ imgs: fileList, detail }, async () => {
      // 更新state后，再提交表单数据
      delete this.state.category
      let item = {}
      if(this.props.location.state) {
        // 更新数据
        item = await http.post('/rest/products/update', this.state)
      } else {
        // 提交数据
        item = await http.post('/rest/products', this.state)
      }
      message.success(item.data.message)
      this.props.history.go(-1)
    })
  }
  // 组件挂载完成
  async componentDidMount() {
    // 创建富文本框
    editor = new E('#div1')
    editor.config.zIndex = 2
    editor.config.uploadImgServer = `${http.defaults.baseURL}/upload`
    editor.config.uploadFileName = 'file'
    editor.create()
    const detail = this.props.location.state ? this.props.location.state.commodity.detail : ''
    editor.txt.html(detail)
    if(detail) this.setState(this.props.location.state.commodity)
    // 获取分类数据
    const item = await http.get('/rest/category/whole')
    this.setState({ category: item.data })
  }
  render() {
    const commodity = this.props.location.state ? this.props.location.state.commodity : ''
    const title = (
      <>
        <Button type="link" onClick={ this.historyGo }>
          <ArrowLeftOutlined />
        </Button>
        <span>添加商品</span>
      </>
    )
    const extra = <Button type="primary" htmlType="submit" onClick={ this.submitForm }>保存</Button>
    return (
      <div className="addupdata">
        <Card title={title} extra={extra} style={{ height: '100%' }}>
          <Form>
            <Item label="商品名称" name="name" initialValue={commodity ? commodity.name : ''} rules={[{required: true, message: '商品名称必须填写'}]}>
              <Input className="input-width" onChange={(e) => { this.setState({ name: e.target.value }) }} />
            </Item>
            <Item label="商品描述" name="desc" initialValue={commodity ? commodity.desc : ''} rules={[{ required: true }]}>
              <Input.TextArea  className="input-width"  onChange={(e) => { this.setState({ desc: e.target.value }) }} />
            </Item>
            <Item label="商品价格" name="price" initialValue={commodity ? commodity.price : ''} rules={[{ required: true }]}>
              <Input className="input-width" placeholder="元" onChange={(e) => { this.setState({ price: Number(e.target.value) }) }} />
            </Item>
            <Item label="商品分类" name="selsct" initialValue={commodity ? commodity.CategoryId._id : ''} rules={[{ required: true }]}>
              <Select style={{ width: 300 }} onChange={value => { this.setState({ CategoryId: value }) }}>
                {
                  this.state.category.map(item => {
                    return <Option value={ item._id } key={item._id}>{ item.name }</Option>
                  })
                }
              </Select>
            </Item>
            <Item label="商品图片">
              <Upload ref={ this.uploadRef } imgs={commodity ? commodity.imgs : []} />
            </Item>
            <Item label="商品详情">
              <div id="div1"></div>
            </Item>
          </Form>
        </Card>
      </div>
    )
  }
}

export default withRouter(AddUpdata)
